<template>
  <ToolbarButton
    type="dropdown"
    icon="i-ri-align-left"
    title="对齐方式"
    :active="isActive"
    popover-placement="bottom-start"
    :large-icon="props.largeIcon"
    :hide-text="props.hideText"
    :disabled="!canSetCellAlign"
  >
    {{ currentAlignLabel }}
    <template #dropdown>
      <DropdownItem
        v-for="option in alignOptions"
        :key="option.value"
        :command="option.value"
        :class="{
          'align-item-active': currentAlign === option.value,
        }"
        @click="setAlign(option.value)"
      >
        {{ option.label }}
      </DropdownItem>
    </template>
  </ToolbarButton>
</template>

<script setup lang="ts">
import { computed, inject, ref, watch, onBeforeUnmount, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import ToolbarButton from "../../../button/index.vue";
import { DropdownItem } from "../../../dropdown";

defineOptions({
  name: "CellAlign",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

const editor = inject<Ref<Editor>>("editor");

// 对齐选项：12种对齐方式
const alignOptions = [
  { value: "left-top", label: "靠上左对齐" },
  { value: "center-top", label: "靠上居中对齐" },
  { value: "right-top", label: "靠上右对齐" },
  { value: "justify-top", label: "靠上两端对齐" },
  { value: "left-middle", label: "中间左对齐" },
  { value: "center-middle", label: "中间居中对齐" },
  { value: "right-middle", label: "中间右对齐" },
  { value: "justify-middle", label: "中间两端对齐" },
  { value: "left-bottom", label: "靠下左对齐" },
  { value: "center-bottom", label: "靠下居中对齐" },
  { value: "right-bottom", label: "靠下右对齐" },
  { value: "justify-bottom", label: "靠下两端对齐" },
];

const currentAlign = ref<string | null>(null);

const isActive = computed(() => {
  if (!editor?.value) return false;

  // 首先检查是否在单元格或表头中
  const inCell = editor.value.isActive("tableCell");
  const inHeader = editor.value.isActive("tableHeader");

  if (!inCell && !inHeader) return false;

  // 检查是否有自定义的 align 属性
  let align: string | null = null;
  if (inCell) {
    const attrs = editor.value.getAttributes("tableCell");
    align = attrs?.align || null;
  } else if (inHeader) {
    const attrs = editor.value.getAttributes("tableHeader");
    align = attrs?.align || null;
  }

  // 只有在单元格/表头中并且有 align 属性时才激活
  return align !== null;
});

const canSetCellAlign = computed(() => {
  if (!editor?.value) return false;
  return (
    editor.value.isActive("tableCell") || editor.value.isActive("tableHeader")
  );
});

// 获取当前对齐方式
const getCurrentAlign = () => {
  if (!editor?.value) return null;

  if (editor.value.isActive("tableCell")) {
    const attrs = editor.value.getAttributes("tableCell");
    return attrs?.align || null;
  }

  if (editor.value.isActive("tableHeader")) {
    const attrs = editor.value.getAttributes("tableHeader");
    return attrs?.align || null;
  }

  return null;
};

// 获取当前对齐方式的标签
const currentAlignLabel = computed(() => {
  if (!currentAlign.value) {
    return "对齐方式";
  }
  const option = alignOptions.find((opt) => opt.value === currentAlign.value);
  return option?.label || "对齐方式";
});

// 更新当前对齐方式
const updateCurrentAlign = () => {
  const align = getCurrentAlign();
  currentAlign.value = align;
};

// 监听编辑器变化
watch(
  () => editor?.value,
  (newEditor, oldEditor) => {
    if (oldEditor) {
      oldEditor.off("selectionUpdate", updateCurrentAlign);
      oldEditor.off("transaction", updateCurrentAlign);
    }

    if (newEditor) {
      newEditor.on("selectionUpdate", updateCurrentAlign);
      newEditor.on("transaction", updateCurrentAlign);
      updateCurrentAlign();
    }
  },
  { immediate: true }
);

// 组件卸载时清理事件监听器
onBeforeUnmount(() => {
  if (editor?.value && updateCurrentAlign) {
    editor.value.off("selectionUpdate", updateCurrentAlign);
    editor.value.off("transaction", updateCurrentAlign);
  }
});

// 设置对齐方式
const setAlign = (align: string | null) => {
  if (!editor?.value) return;

  if (align === null) {
    // 清除对齐（使用默认值）
    editor.value.chain().focus().setCellAttribute("align", null).run();
  } else {
    // 设置对齐
    editor.value.chain().focus().setCellAttribute("align", align).run();
  }

  currentAlign.value = align;
};
</script>

<style scoped lang="scss">
:deep(.align-item-active) {
  color: var(--editor-primary-color);
  background-color: var(--editor-button-hover-background, #f2f2f2);
}
</style>
